package org.znxs.znxsframe.controller;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程队列测试接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/queen")
@Slf4j
@Profile({"dev","local"})
public class QueueController {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @PostMapping("/add")
    public void addWork(@RequestParam(value = "workName") String workName){
        CompletableFuture.runAsync(()->{
            log.info("任务执行中"+workName+",执行人："+Thread.currentThread().getName());
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },threadPoolExecutor);
    }

    @GetMapping("/get")
    public String getWork(){
        HashMap<String, Object> threadMap = new HashMap<>();
        int queueSize = threadPoolExecutor.getQueue().size();
        threadMap.put("队列长度",queueSize);
        int activeCount = threadPoolExecutor.getActiveCount();
        threadMap.put("正在工作线程数",activeCount);
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        threadMap.put("已完成工作数",completedTaskCount);
        long taskCount = threadPoolExecutor.getTaskCount();
        threadMap.put("任务总数",taskCount);
        return JSONUtil.toJsonStr(threadMap);
    }

}
